package com.github.linkoog.model_designer.ide.editer.dbtable.tab_editer;

import com.github.linkoog.model_designer.ide.type.TableYamlFileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.newvfs.BulkFileListener;
import com.intellij.openapi.vfs.newvfs.events.VFileEvent;
import com.intellij.util.messages.MessageBusConnection;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public class DBTableTabPanelEventInjector implements BulkFileListener {

    private Project project;

    public DBTableTabPanelEventInjector(Project project){
        this.project = project;
        MessageBusConnection messageBusConnection = project.getMessageBus().connect(project);
        messageBusConnection.subscribe(VirtualFileManager.VFS_CHANGES, this);
    }

    /**
     *   文件编辑保存后，更新可视化面板
     */
    @Override
    public void after(@NotNull List<? extends @NotNull VFileEvent> events) {
        for (VFileEvent event : events) {
            final VirtualFile virtualFile = event.getFile();
            if (!event.isFromSave() || virtualFile == null ||  !(virtualFile.getFileType() instanceof TableYamlFileType)){
                continue;
            }

            final DBTableLeftPanel dbTableLeftPanel = virtualFile.getUserData(DBTableLeftPanel.LEFT_PANEL_KEY);
            if ( dbTableLeftPanel == null){
                continue;
            }

            dbTableLeftPanel.resetPanelContext();
            break;
        }
    }
}
